// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.DataIndex;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.PageSearchFilter;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.StockOut;
import com.fowo.api.entity.StockOutProduct;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.inventory.model.InventoryOutboundVo;
import com.fowo.api.inventory.model.PatternEnum;
import com.fowo.api.inventory.model.SimpleInventoryItem;
import com.fowo.api.inventory.model.TargetTypeEnum;
import com.fowo.api.inventory.model.form.InventoryOutboundFormVo;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.mapper.DbOrganizationMapper;
import com.fowo.api.mapper.ListingFatherMapper;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.StockOutMapper;
import com.fowo.api.mapper.StockOutProductMapper;
import com.fowo.api.mapper.WarehouseBinMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.db.organization.DbOrganizationItemVo;
import com.fowo.api.model.db.organization.DbOrganizationSearchParamPo;
import com.fowo.api.model.listing.father.ListingFatherItemVo;
import com.fowo.api.model.listing.father.ListingFatherSearchParamPo;
import com.fowo.api.model.product.ProductItemVo;
import com.fowo.api.model.product.ProductSearchParamPo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.stock.out.StockOutAndStockOutProductImportPo;
import com.fowo.api.model.stock.out.StockOutBatchPushLingXingAction;
import com.fowo.api.model.stock.out.StockOutConfirmOutboundBatchAction;
import com.fowo.api.model.stock.out.StockOutCreateReceivableAction;
import com.fowo.api.model.stock.out.StockOutExcelPo;
import com.fowo.api.model.stock.out.StockOutImportPo;
import com.fowo.api.model.stock.out.StockOutItemVo;
import com.fowo.api.model.stock.out.StockOutOmitAction;
import com.fowo.api.model.stock.out.StockOutPushLingXingAction;
import com.fowo.api.model.stock.out.StockOutPushStockInAndStockOutAction;
import com.fowo.api.model.stock.out.StockOutPushStockOutAction;
import com.fowo.api.model.stock.out.StockOutReferAction;
import com.fowo.api.model.stock.out.StockOutSearchParamPo;
import com.fowo.api.model.stock.out.StockOutVo;
import com.fowo.api.model.stock.out.constant.StockOutAStatusEnums;
import com.fowo.api.model.stock.out.constant.StockOutDocumentStatusEnums;
import com.fowo.api.model.stock.out.constant.StockOutProductTypeEnums;
import com.fowo.api.model.stock.out.product.StockOutProductItemVo;
import com.fowo.api.model.stock.out.product.StockOutProductItemVoPages;
import com.fowo.api.model.stock.out.product.StockOutProductSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.model.warehouse.bin.WarehouseBinItemVo;
import com.fowo.api.model.warehouse.bin.WarehouseBinSearchParamPo;
import com.fowo.api.service.StockOutProductService;
import com.fowo.api.service.StockOutService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.mapper.SysDepartmentMapper;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDepartmentSearchParamPo;
import com.fowo.api.sys.model.SysDepartmentVo;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 出库单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：鹿丙涛，任凯
 */
@Slf4j
@DataObjectType(StockOut.class)
@DS("ds24")
public class StockOutBaseServiceImpl
  extends ServiceImpl<StockOutMapper, StockOut>
  implements StockOutService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("warehouseName", "w.`name`");
      put("createUserName", "su.`name`");
      put("toWarehouseName", "w2.`name`");
      put("deptName", "sd.`name`");
      put("customerShopName", "si.`shop_name`");
      put("needOrgName", "do.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected StockOutService self;

  @Resource
  protected StockOutProductService stockOutProductService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected SysDepartmentMapper sysDepartmentMapper;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected DbOrganizationMapper dbOrganizationMapper;

  @Resource
  private StockOutProductMapper childMapper;

  @Resource
  protected ProductMapper productMapper;

  @Resource
  protected ListingFatherMapper listingFatherMapper;

  @Resource
  protected WarehouseBinMapper warehouseBinMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected InventoryBusinessService inventoryBusinessService;

  @Autowired(required = false)
  protected StockOutReferAction stockOutReferAction;

  @Autowired(required = false)
  protected StockOutConfirmOutboundBatchAction stockOutConfirmOutboundBatchAction;

  @Autowired(required = false)
  protected StockOutBatchPushLingXingAction stockOutBatchPushLingXingAction;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Autowired(required = false)
  protected StockOutOmitAction stockOutOmitAction;

  @Autowired(required = false)
  protected StockOutPushLingXingAction stockOutPushLingXingAction;

  @Autowired(required = false)
  protected StockOutPushStockOutAction stockOutPushStockOutAction;

  @Autowired(required = false)
  protected StockOutPushStockInAndStockOutAction stockOutPushStockInAndStockOutAction;

  @Autowired(required = false)
  protected StockOutCreateReceivableAction stockOutCreateReceivableAction;

  @Resource
  protected Validator validator;

  /**
   * 创建出库单
   * @param model 出库单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(StockOutVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    StockOut entity = new StockOut();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getType() == null) {
      entity.setType("CK002");
    }

    if (model.getProductType() == null) {
      entity.setProductType("1");
    }

    if (model.getStatus() == null) {
      entity.setStatus("CS01");
    }

    if (model.getIsPush() == null) {
      entity.setIsPush(false);
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getOrderSn())) {
      entity.setOrderSn(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "StockOut.orderSn")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return entity.getId();
    }
    throw new Exception("出库单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 出库单
   */
  protected void updateAllChilds(StockOutVo model) throws Exception {
    if (model.getStockOutProducts() != null) {
      stockOutProductService.saveAllByStockOutId(
        model.getId(),
        model.getStockOutProducts()
      );
    }
  }

  /**
   * 更新出库单
   * @param model 出库单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(StockOutVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    StockOut entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("出库单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "lastUpdateTime",
      "lastUpdateUser",
      "orderSn",
      "createUser",
      "createTime",
      "totalNum",
      "parentId",
      "totalAmount",
      "status"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return true;
    }
    return false;
  }/**
   * 更新出库单（带空值）
   * @param model 出库单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(StockOutVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    StockOut entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("出库单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(StockOut::getLastUpdateTime, model.getLastUpdateTime())
      .set(StockOut::getLastUpdateUser, model.getLastUpdateUser())
      .set(StockOut::getWarehouse, model.getWarehouse())
      .set(StockOut::getType, model.getType())
      .set(StockOut::getOutTime, model.getOutTime())
      .set(StockOut::getDept, model.getDept())
      .set(StockOut::getProductType, model.getProductType())
      .set(StockOut::getRemark, model.getRemark())
      .set(StockOut::getNeedOrg, model.getNeedOrg())
      .set(StockOut::getCustomSourceSn, model.getCustomSourceSn())
      .set(StockOut::getGoodsValue, model.getGoodsValue())
      .set(StockOut::getGoodsCost, model.getGoodsCost())
      .set(StockOut::getCephalicProcess, model.getCephalicProcess())
      .eq(StockOut::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(model.getId());
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(StockOutSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 出库单子表(stockOutProducts) 对应的对象
    StockOutProductSearchParamPo stockOutProductsSearchParam =
      new StockOutProductSearchParamPo();
    stockOutProductsSearchParam.setDisableDataPremissions(true);
    stockOutProductsSearchParam.setStockOutIdInList(ids);
    StockOutProductMapper localStockOutProductMapper = ContextHolder
      .getApplicationContext()
      .getBean(StockOutProductMapper.class);
    stockOutProductsSearchParam.applySqlSegments();
    List<Long> stockOutProductsIdList = localStockOutProductMapper.searchIds(
      stockOutProductsSearchParam
    );
    if (!stockOutProductsIdList.isEmpty()) {
      StockOutProductService localStockOutProductService = ContextHolder
        .getApplicationContext()
        .getBean(StockOutProductService.class);
      localStockOutProductService.batchDelete(stockOutProductsIdList);
    }
    // FIXME: 未找到子表字段 采购信息(procurementInformation) 对应的对象，忽略删除处理！
  }

  /**
   * 删除出库单
   * @param id 出库单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除出库单
   * @param ids 出库单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<StockOutImportPo> excelToImportRow(
    StockOutImportPo row,
    Integer rowNumber,
    StockOutVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<StockOutImportPo> ir = new ImportRow<StockOutImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<StockOutImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new StockOutVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, StockOutImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getType())) {
      List<SysDictAllItem> typeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "type",
          n -> sysDictService.getDictItems("SCM00022")
        );
      StockOutVo finalVo = vo;
      typeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setType(i.getItemValue()),
          () ->
            ir.addError(
              "type",
              String.format(
                "必须为 %s 中之一",
                typeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setOutTime(SheetUtils.tryToDateTime(row.getOutTime()));
    if (StringUtils.hasText(row.getDocumentStatus())) {
      vo.setDocumentStatus(
        StockOutDocumentStatusEnums.toValue(row.getDocumentStatus())
      );
      if (vo.getDocumentStatus() == null) {
        ir.addError(
          "documentStatus",
          "单据状态只能是：“待提交”, “待出库”, “已完成”, “已撤销”"
        );
      }
    }
    if (StringUtils.hasText(row.getProductType())) {
      vo.setProductType(StockOutProductTypeEnums.toValue(row.getProductType()));
      if (vo.getProductType() == null) {
        ir.addError("productType", "产品类型只能是：“原材料”, “成品”");
      }
    }
    if (StringUtils.hasText(row.getStatus())) {
      List<SysDictAllItem> statusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "status",
          n -> sysDictService.getDictItems("SCM00023")
        );
      StockOutVo finalVo = vo;
      statusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStatus(i.getItemValue()),
          () ->
            ir.addError(
              "status",
              String.format(
                "必须为 %s 中之一",
                statusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getAddType())) {
      List<SysDictAllItem> addTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "addType",
          n -> sysDictService.getDictItems("SCM00035")
        );
      StockOutVo finalVo = vo;
      addTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getAddType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setAddType(i.getItemValue()),
          () ->
            ir.addError(
              "addType",
              String.format(
                "必须为 %s 中之一",
                addTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getAStatus())) {
      vo.setAStatus(StockOutAStatusEnums.toValue(row.getAStatus()));
      if (vo.getAStatus() == null) {
        ir.addError(
          "aStatus",
          "审批状态只能是：“待提交”, “待出库”, “已完成”, “已撤销”, “待审批”, “已驳回”"
        );
      }
    }
    vo.setRId(SheetUtils.tryToLong(row.getRId()));
    vo.setIsPush(SheetUtils.tryToBoolean(row.getIsPush()));
    vo.setGoodsValue(SheetUtils.tryToDecimal(row.getGoodsValue()));
    vo.setGoodsCost(SheetUtils.tryToDecimal(row.getGoodsCost()));
    vo.setCephalicProcess(SheetUtils.tryToDecimal(row.getCephalicProcess()));
    // 处理关联字段“出库仓库”
    if (
      !SheetUtils.isBlank(row.getWarehouseName()) &&
      SheetUtils.isBlank(row.getWarehouse())
    ) {
      WarehouseSearchParamPo warehouseSearchParam =
        new WarehouseSearchParamPo();
      warehouseSearchParam.setLimit(2); // 最大只返回二行记录
      warehouseSearchParam.setNameEq(SheetUtils.trim(row.getWarehouseName()));
      warehouseSearchParam.setFinalFilters(new ArrayList<>());
      warehouseSearchParam
        .getFinalFilters()
        .add(
          new PageSearchFilter()
            .setDataIndex(new DataIndex("widType"))
            .setOp("eq")
            .setValue("1")
        );
      warehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> warehouseMatches = warehouseMapper.search(
        warehouseSearchParam
      );
      if (warehouseMatches.size() == 0) {
        ir.addError("warehouseName", "未能在仓库即时库存中找到匹配的数据");
      } else if (warehouseMatches.size() > 1) {
        ir.addError(
          "warehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setWarehouse(warehouseMatches.get(0).getId());
      }
    }
    // 处理关联字段“目标仓库”
    if (
      !SheetUtils.isBlank(row.getToWarehouseName()) &&
      SheetUtils.isBlank(row.getToWarehouse())
    ) {
      WarehouseSearchParamPo toWarehouseSearchParam =
        new WarehouseSearchParamPo();
      toWarehouseSearchParam.setLimit(2); // 最大只返回二行记录
      toWarehouseSearchParam.setNameEq(
        SheetUtils.trim(row.getToWarehouseName())
      );
      toWarehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> toWarehouseMatches = warehouseMapper.search(
        toWarehouseSearchParam
      );
      if (toWarehouseMatches.size() == 0) {
        ir.addError("toWarehouseName", "未能在仓库即时库存中找到匹配的数据");
      } else if (toWarehouseMatches.size() > 1) {
        ir.addError(
          "toWarehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setToWarehouse(toWarehouseMatches.get(0).getId());
      }
    }
    // 处理关联字段“组织”
    if (
      !SheetUtils.isBlank(row.getDeptName()) &&
      SheetUtils.isBlank(row.getDept())
    ) {
      SysDepartmentSearchParamPo deptSearchParam =
        new SysDepartmentSearchParamPo();
      deptSearchParam.setLimit(2); // 最大只返回二行记录
      deptSearchParam.setNameEq(SheetUtils.trim(row.getDeptName()));
      deptSearchParam.applySqlSegments();
      List<SysDepartmentVo> deptMatches = sysDepartmentMapper.search(
        deptSearchParam
      );
      if (deptMatches.size() == 0) {
        ir.addError("deptName", "未能在部门中找到匹配的数据");
      } else if (deptMatches.size() > 1) {
        ir.addError("deptName", "关联不唯一，在部门中找到多个匹配的数据");
      } else {
        vo.setDept(deptMatches.get(0).getId());
      }
    }
    // 处理关联字段“客户”
    if (
      !SheetUtils.isBlank(row.getCustomerShopName()) &&
      SheetUtils.isBlank(row.getCustomer())
    ) {
      ShopInfoSearchParamPo customerSearchParam = new ShopInfoSearchParamPo();
      customerSearchParam.setLimit(2); // 最大只返回二行记录
      customerSearchParam.setShopNameEq(
        SheetUtils.trim(row.getCustomerShopName())
      );
      customerSearchParam.applySqlSegments();
      List<ShopInfoItemVo> customerMatches = shopInfoMapper.search(
        customerSearchParam
      );
      if (customerMatches.size() == 0) {
        ir.addError("customerShopName", "未能在店铺中找到匹配的数据");
      } else if (customerMatches.size() > 1) {
        ir.addError(
          "customerShopName",
          "关联不唯一，在店铺中找到多个匹配的数据"
        );
      } else {
        vo.setCustomer(customerMatches.get(0).getId());
      }
    }
    // 处理关联字段“结算组织”
    if (
      !SheetUtils.isBlank(row.getNeedOrgName()) &&
      SheetUtils.isBlank(row.getNeedOrg())
    ) {
      DbOrganizationSearchParamPo needOrgSearchParam =
        new DbOrganizationSearchParamPo();
      needOrgSearchParam.setLimit(2); // 最大只返回二行记录
      needOrgSearchParam.setNameEq(SheetUtils.trim(row.getNeedOrgName()));
      needOrgSearchParam.applySqlSegments();
      List<DbOrganizationItemVo> needOrgMatches = dbOrganizationMapper.search(
        needOrgSearchParam
      );
      if (needOrgMatches.size() == 0) {
        ir.addError("needOrgName", "未能在组织中找到匹配的数据");
      } else if (needOrgMatches.size() > 1) {
        ir.addError("needOrgName", "关联不唯一，在组织中找到多个匹配的数据");
      } else {
        vo.setNeedOrg(needOrgMatches.get(0).getId());
      }
    }
    // 子表导入处理
    if (
      row.getStockOutProducts() != null && !row.getStockOutProducts().isEmpty()
    ) {
      List<ImportRow<StockOutAndStockOutProductImportPo>> handledChildRows =
        new ArrayList<>();
      StockOutProductItemVo childVo = new StockOutProductItemVo();
      for (ImportRow<StockOutAndStockOutProductImportPo> childRowPo : row.getStockOutProducts()) {
        final ImportRow<StockOutAndStockOutProductImportPo> childImportRow =
          excelToImportChildRow(
            ir,
            childRowPo.getRow(),
            childRowPo.getRowNumber(),
            vo,
            childVo,
            variables
          );
        handledChildRows.add(childImportRow);
      }
      row.setStockOutProducts(handledChildRows);
    }

    return ir;
  }

  /**
   * 子表导入处理
   */
  protected ImportRow<StockOutAndStockOutProductImportPo> excelToImportChildRow(
    ImportRow<StockOutImportPo> parentRow,
    StockOutAndStockOutProductImportPo row,
    Integer rowNumber,
    StockOutVo parentVo,
    StockOutProductItemVo vo,
    Map<String, Object> variables
  ) {
    ImportRow<StockOutAndStockOutProductImportPo> ir = new ImportRow<>();
    ir.setParentRowNumber(parentRow.getRowNumber());
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<StockOutAndStockOutProductImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new StockOutProductItemVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, StockOutAndStockOutProductImportPo.class);

    // 一般数据处理
    vo.setGoodNum(SheetUtils.tryToLong(row.getGoodNum()));
    vo.setProductGoodNum(SheetUtils.tryToInteger(row.getProductGoodNum()));
    vo.setBadNum(SheetUtils.tryToLong(row.getBadNum()));
    vo.setProductBadNum(SheetUtils.tryToInteger(row.getProductBadNum()));
    vo.setWaitShipments(SheetUtils.tryToInteger(row.getWaitShipments()));
    vo.setPrice(SheetUtils.tryToDecimal(row.getPrice()));
    vo.setCostPrice(SheetUtils.tryToDecimal(row.getCostPrice()));
    vo.setMainUnitPrice(SheetUtils.tryToDecimal(row.getMainUnitPrice()));
    vo.setGramWeight(SheetUtils.tryToDecimal(row.getGramWeight()));
    vo.setLaborCosts(SheetUtils.tryToDecimal(row.getLaborCosts()));
    vo.setAccessoriesPrice(SheetUtils.tryToDecimal(row.getAccessoriesPrice()));
    vo.setQuantity(SheetUtils.tryToInteger(row.getQuantity()));
    vo.setSingleFee(SheetUtils.tryToDecimal(row.getSingleFee()));
    vo.setSingleStockCost(SheetUtils.tryToDecimal(row.getSingleStockCost()));
    vo.setUnitHeadFee(SheetUtils.tryToDecimal(row.getUnitHeadFee()));
    vo.setProductAmounts(SheetUtils.tryToDecimal(row.getProductAmounts()));
    vo.setFeeCost(SheetUtils.tryToDecimal(row.getFeeCost()));
    vo.setHeadWayFee(SheetUtils.tryToDecimal(row.getHeadWayFee()));
    vo.setAmount(SheetUtils.tryToDecimal(row.getAmount()));
    vo.setSubtotal(SheetUtils.tryToDecimal(row.getSubtotal()));
    vo.setCurrentIssueCostAmount(
      SheetUtils.tryToDecimal(row.getCurrentIssueCostAmount())
    );
    vo.setTotal(SheetUtils.tryToInteger(row.getTotal()));
    vo.setCrossQty(SheetUtils.tryToInteger(row.getCrossQty()));
    vo.setOutboundValue(SheetUtils.tryToDecimal(row.getOutboundValue()));
    vo.setOutboundValueCost(
      SheetUtils.tryToDecimal(row.getOutboundValueCost())
    );
    vo.setEphalicProcess(SheetUtils.tryToDecimal(row.getEphalicProcess()));
    // 处理关联字段“品名”
    if (
      !SheetUtils.isBlank(row.getProductIdName()) &&
      SheetUtils.isBlank(row.getProductId())
    ) {
      ProductSearchParamPo productIdSearchParam = new ProductSearchParamPo();
      productIdSearchParam.setLimit(2); // 最大只返回二行记录
      productIdSearchParam.setNameEq(SheetUtils.trim(row.getProductIdName()));
      productIdSearchParam.applySqlSegments();
      List<ProductItemVo> productIdMatches = productMapper.search(
        productIdSearchParam
      );
      if (productIdMatches.size() == 0) {
        ir.addError("productIdName", "未能在产品管理中找到匹配的数据");
      } else if (productIdMatches.size() > 1) {
        ir.addError(
          "productIdName",
          "关联不唯一，在产品管理中找到多个匹配的数据"
        );
      } else {
        vo.setProductId(productIdMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", productIdMatches.get(0).getId())
          .put("fromObjectName", "StockOut")
          .put("fromObjectId", vo.getId())
          .put("fromField", "productId")
          .put("fromParentObjectName", "productId")
          .put("fromParentObjectId", parentVo.getId())
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(3);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("sku")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("sku")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("sku")
              .rowFieldName("sku")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains(
              "productName"
            )
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("name")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("productName")
              .rowFieldName("productName")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("productImg")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("picUrl")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("productImg")
              .rowFieldName(null)
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          parentRow,
          ir,
          parentVo,
          vo,
          CollUtil.getFirst(productIdMatches),
          joinModels
        );
      }
    }
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getSidShopName()) &&
      SheetUtils.isBlank(row.getSid())
    ) {
      ShopInfoSearchParamPo sidSearchParam = new ShopInfoSearchParamPo();
      sidSearchParam.setLimit(2); // 最大只返回二行记录
      sidSearchParam.setShopNameEq(SheetUtils.trim(row.getSidShopName()));
      sidSearchParam.applySqlSegments();
      List<ShopInfoItemVo> sidMatches = shopInfoMapper.search(sidSearchParam);
      if (sidMatches.size() == 0) {
        ir.addError("sidShopName", "未能在店铺中找到匹配的数据");
      } else if (sidMatches.size() > 1) {
        ir.addError("sidShopName", "关联不唯一，在店铺中找到多个匹配的数据");
      } else {
        vo.setSid(sidMatches.get(0).getId());
      }
    }
    // 处理关联字段“FNSKU”
    if (
      !SheetUtils.isBlank(row.getFnskuIdFnsku()) &&
      SheetUtils.isBlank(row.getFnskuId())
    ) {
      ListingFatherSearchParamPo fnskuIdSearchParam =
        new ListingFatherSearchParamPo();
      fnskuIdSearchParam.setLimit(2); // 最大只返回二行记录
      fnskuIdSearchParam.setFnskuEq(SheetUtils.trim(row.getFnskuIdFnsku()));
      fnskuIdSearchParam.setFinalFilters(new ArrayList<>());
      fnskuIdSearchParam.applySqlSegments();
      List<ListingFatherItemVo> fnskuIdMatches = listingFatherMapper.search(
        fnskuIdSearchParam
      );
      if (fnskuIdMatches.size() == 0) {
        ir.addError("fnskuIdFnsku", "未能在Listing中找到匹配的数据");
      } else if (fnskuIdMatches.size() > 1) {
        ir.addError(
          "fnskuIdFnsku",
          "关联不唯一，在Listing中找到多个匹配的数据"
        );
      } else {
        vo.setFnskuId(fnskuIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“可用仓位”
    if (
      !SheetUtils.isBlank(row.getStorageBinGoodIdStorageBin()) &&
      SheetUtils.isBlank(row.getStorageBinGoodId())
    ) {
      WarehouseBinSearchParamPo storageBinGoodIdSearchParam =
        new WarehouseBinSearchParamPo();
      storageBinGoodIdSearchParam.setLimit(2); // 最大只返回二行记录
      storageBinGoodIdSearchParam.setStorageBinEq(
        SheetUtils.trim(row.getStorageBinGoodIdStorageBin())
      );
      storageBinGoodIdSearchParam.applySqlSegments();
      List<WarehouseBinItemVo> storageBinGoodIdMatches =
        warehouseBinMapper.search(storageBinGoodIdSearchParam);
      if (storageBinGoodIdMatches.size() == 0) {
        ir.addError("storageBinGoodIdStorageBin", "未能在仓位中找到匹配的数据");
      } else if (storageBinGoodIdMatches.size() > 1) {
        ir.addError(
          "storageBinGoodIdStorageBin",
          "关联不唯一，在仓位中找到多个匹配的数据"
        );
      } else {
        vo.setStorageBinGoodId(storageBinGoodIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“次品仓位”
    if (
      !SheetUtils.isBlank(row.getStorageBinBadIdStorageBin()) &&
      SheetUtils.isBlank(row.getStorageBinBadId())
    ) {
      WarehouseBinSearchParamPo storageBinBadIdSearchParam =
        new WarehouseBinSearchParamPo();
      storageBinBadIdSearchParam.setLimit(2); // 最大只返回二行记录
      storageBinBadIdSearchParam.setStorageBinEq(
        SheetUtils.trim(row.getStorageBinBadIdStorageBin())
      );
      storageBinBadIdSearchParam.applySqlSegments();
      List<WarehouseBinItemVo> storageBinBadIdMatches =
        warehouseBinMapper.search(storageBinBadIdSearchParam);
      if (storageBinBadIdMatches.size() == 0) {
        ir.addError("storageBinBadIdStorageBin", "未能在仓位中找到匹配的数据");
      } else if (storageBinBadIdMatches.size() > 1) {
        ir.addError(
          "storageBinBadIdStorageBin",
          "关联不唯一，在仓位中找到多个匹配的数据"
        );
      } else {
        vo.setStorageBinBadId(storageBinBadIdMatches.get(0).getId());
      }
    }
    // 计算数据处理
    SheetUtils.calculateField(
      row,
      vo,
      "getValue('mainUnitPrice') * getValue('gramWeight')+getValue('laborCosts') ",
      "price"
    );
    // 计算数据处理
    SheetUtils.calculateField(
      row,
      vo,
      "getValue('mainUnitPrice') * getValue('gramWeight')+getValue('laborCosts') +getValue('accessoriesPrice') ",
      "costPrice"
    );
    // 计算数据处理
    SheetUtils.calculateField(
      row,
      vo,
      "getValue('productGoodNum') +getValue('productBadNum') ",
      "quantity"
    );
    // 计算数据处理
    SheetUtils.calculateField(
      row,
      vo,
      "(getValue('quantity') * getValue('price')).toFixed(2)",
      "subtotal"
    );
    // 计算数据处理
    SheetUtils.calculateField(
      row,
      vo,
      "getValue('quantity') * getValue('price')",
      "currentIssueCostAmount"
    );
    // 计算数据处理
    SheetUtils.calculateField(
      row,
      vo,
      "getValue('quantity') * getValue('price')",
      "total"
    );
    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<StockOutImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<StockOutImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            StockOutImportPo.class,
            StockOutAndStockOutProductImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(StockOutImportPo row, AnalysisContext cxt) {
              StockOutVo vo = new StockOutVo();
              ImportRow<StockOutImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<StockOutImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<StockOutImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      StockOutVo vo = new StockOutVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"出库单号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "orderSn".equals(m.getField())
          )
      ) {
        vo.setOrderSn(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "StockOut.orderSn")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      // 子表数据处理
      importChild(vo, row, i, variables);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  protected void importChild(
    StockOutVo vo,
    ImportRow<StockOutImportPo> row,
    int i,
    Map<String, Object> variables
  ) {
    if (
      row.getRow().getStockOutProducts() == null ||
      row.getRow().getStockOutProducts().isEmpty()
    ) {
      return;
    }
    for (ImportRow<StockOutAndStockOutProductImportPo> childRow : row
      .getRow()
      .getStockOutProducts()) {
      StockOutProductItemVo itemVo = new StockOutProductItemVo();
      final ImportRow<StockOutAndStockOutProductImportPo> rowChild =
        excelToImportChildRow(
          row,
          childRow.getRow(),
          childRow.getRowNumber(),
          vo,
          itemVo,
          variables
        );
      itemVo.setId(childRow.getUpdateId());
      if (rowChild.getErrors() != null && rowChild.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            rowChild.getRowNumber(),
            rowChild.getJoinErrorMessage()
          )
        );
      }
      if (vo.getStockOutProducts() == null) {
        vo.setStockOutProducts(new ArrayList<>());
      }
      vo.getStockOutProducts().add(itemVo);
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    StockOutSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.setChildMappingOption(
        new CustomExcelExport.ChildMappingOption()
          .setFieldName("stockOutProducts")
          .setChildPageSearch((parentRecord, current, pageSize) -> {
            StockOutItemVo parent = (StockOutItemVo) parentRecord;
            StockOutProductSearchParamPo searchParamPo =
              new StockOutProductSearchParamPo();
            searchParamPo.setCurrent(current);
            searchParamPo.setPageSize(pageSize);
            searchParamPo.setStockOutIdEq(parent.getId());
            return stockOutProductService.pageSearch(searchParamPo);
          })
      );
      exportOptions.addFieldMappingOption(
        "stockOutProducts.productId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockOutProductItemVo) r).getProductIdName())
          )
      );
      exportOptions.addFieldMappingOption(
        "stockOutProducts.sid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockOutProductItemVo) r).getSidShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "stockOutProducts.fnskuId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockOutProductItemVo) r).getFnskuIdFnsku())
          )
      );
      exportOptions.addFieldMappingOption(
        "stockOutProducts.storageBinGoodId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((StockOutProductItemVo) r).getStorageBinGoodIdStorageBin()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "stockOutProducts.storageBinBadId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((StockOutProductItemVo) r).getStorageBinBadIdStorageBin()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "stockOutProducts.stockOutId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockOutProductItemVo) r).getStockOutIdOrderSn())
          )
      );
      exportOptions.addFieldMappingOption(
        "warehouse",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockOutItemVo) r).getWarehouseName())
          )
      );
      exportOptions.addFieldMappingOption(
        "type",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00022")
      );
      exportOptions.addFieldMappingOption(
        "dept",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockOutItemVo) r).getDeptName())
          )
      );
      exportOptions.addFieldMappingOption(
        "productType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> StockOutProductTypeEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00023")
      );
      exportOptions.addFieldMappingOption(
        "needOrg",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((StockOutItemVo) r).getNeedOrgName())
          )
      );
      exportOptions.addStringFields(
        "formId.productIdName",
        "formId.sku",
        "formId.sidShopName",
        "formId.fnskuIdFnsku",
        "formId.storageBinGoodIdStorageBin",
        "formId.storageBinBadIdStorageBin",
        "formId.stockOutIdOrderSn",
        "formId.productName",
        "formId.batchNo",
        "orderSn",
        "warehouseName",
        "type",
        "totalNum",
        "totalAmount",
        "deptName",
        "productType",
        "status",
        "remark",
        "needOrgName",
        "customSourceSn"
      );

      String fileName = String.format(
        "出库单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> typeItems = sysDictService.getDictItems("SCM00022");
    List<SysDictAllItem> statusItems = sysDictService.getDictItems("SCM00023");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<StockOutExcelPo> items = new ArrayList<StockOutExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<StockOutItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<StockOutItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (StockOutItemVo item : list) {
        StockOutExcelPo excel = new StockOutExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getType() != null) {
          typeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getType()))
            .findFirst()
            .ifPresent(i -> excel.setType(i.getItemText()));
        }
        excel.setProductType(
          StockOutProductTypeEnums.toLabel(item.getProductType())
        );
        if (item.getStatus() != null) {
          statusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStatus()))
            .findFirst()
            .ifPresent(i -> excel.setStatus(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "出库单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(StockOutExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过出库单号查询出库单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByOrderSn(String orderSn) {
    return this.baseMapper.getIdByOrderSn(orderSn);
  }

  /**
   * 通过出库单号查询出库单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByOrderSn(List<String> list) {
    return this.baseMapper.getIdsByOrderSn(list);
  }

  /**
   * 通过出库单主键查询出库单号
   */
  @Override
  public String getOrderSnById(Long id) {
    return this.baseMapper.getOrderSnById(id);
  }

  /**
   * 通过出库单主键查询出库单号列表
   */
  @Override
  public List<String> getOrderSnByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getOrderSnByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("orderSn"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 出库单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public StockOutVo getVoById(Long id) throws Exception {
    StockOutVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    StockOutProductSearchParamPo stockOutProductsSearchParamPo =
      new StockOutProductSearchParamPo();
    stockOutProductsSearchParamPo.setStockOutId(id);
    stockOutProductsSearchParamPo.getExtendData().put("queryMode", "sub");
    stockOutProductsSearchParamPo
      .getExtendData()
      .put("queryParent", "StockOut");
    stockOutProductsSearchParamPo.applySqlSegments();
    vo.setStockOutProducts(
      stockOutProductService.search(stockOutProductsSearchParamPo)
    );

    return vo;
  }

  /**
   * 分页查询出库单
   * @param search 查询条件
   * @return 出库单分页查询结果
   */
  @Override
  public Page<StockOutItemVo> pageSearch(StockOutSearchParamPo search) {
    Page<StockOutItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(StockOutItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<StockOutItemVo> pageResult) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<StockOutItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    StockOutProductSearchParamPo stockOutProductsSearchParamPo =
      new StockOutProductSearchParamPo();
    stockOutProductsSearchParamPo.setSort(sort);
    stockOutProductsSearchParamPo.setPageSize(200);
    stockOutProductsSearchParamPo.setStockOutIdInList(
      pageResult
        .getRecords()
        .stream()
        .map(StockOutItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<StockOutProductItemVoPages>> stockOutProductsMaps =
      stockOutProductService.pagesByStockOutId(stockOutProductsSearchParamPo);

    for (StockOutItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put(
        "stockOutProducts",
        stockOutProductsMaps.get(itemVo.getId().toString())
      );
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 出库单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(StockOutSearchParamPo search) {
    return appendWithChild(
      pageSearch(search),
      search.toChildSort("stockOutProducts")
    );
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    StockOutSearchParamPo search
  ) {
    StockOutSearchParamPo parentSearchParam = new StockOutSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<StockOutItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      StockOutItemVo itemVo = parentList.get(0);

      StockOutProductSearchParamPo stockOutProductsSearchParamPo =
        new StockOutProductSearchParamPo();
      stockOutProductsSearchParamPo.setPageSize(search.getPageSize());
      stockOutProductsSearchParamPo.setCurrent(search.getCurrent());
      stockOutProductsSearchParamPo.setStockOutId(itemVo.getId());
      return stockOutProductService.pageSearch(stockOutProductsSearchParamPo);
    } else {
      return null;
    }
  }

  /**
   * 出库单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'StockOutOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<StockOutItemVo>> searchOptions(
    StockOutSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询出库单
   * @param search 查询条件
   * @return 出库单列表查询结果
   */
  @Override
  public List<StockOutItemVo> search(StockOutSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询出库单最后更新时间
   * @param search 查询条件
   * @return 出库单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(StockOutSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 返回满足搜索条件的统计信息
   * @param search 搜索参数
   */
  @Override
  public Map<String, Object> searchForStatistical(
    StockOutSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchForStatistical(search);
  }

  /**
   * 确认出库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了确认出库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void confirmationOfDeliverys(Long id) throws Exception {
    StockOutVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareConfirmationOfDeliverys(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    StockOut updateStatusEntity = new StockOut();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("CS02");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 确认出库 的参数
   */
  protected InventoryOutboundFormVo prepareConfirmationOfDeliverys(
    StockOutVo vo
  ) throws Exception {
    if (!"CS01".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(StockOutVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setSupportNegative(true);
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (StockOutProductItemVo stockOutProduct : vo.getStockOutProducts()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockOutProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(stockOutProduct.getQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockOutProduct.getQuantity())
      );
      outboundItem.setShopId(
        String.valueOf(stockOutProduct.getSid()).equals("null")
          ? null
          : String.valueOf(stockOutProduct.getSid())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            stockOutProduct.getFnsku() == null
              ? null
              : stockOutProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(stockOutProduct.getFnsku().trim())
      );
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(stockOutProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 撤销
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了撤销操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void annul(Long id) throws Exception {
    StockOutVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareAnnul(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    StockOut updateStatusEntity = new StockOut();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("CS04");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 撤销 的参数
   */
  protected InventoryOutboundFormVo prepareAnnul(StockOutVo vo)
    throws Exception {
    if (!"CS02".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(StockOutVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消出库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("撤销出库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (StockOutProductItemVo stockOutProduct : vo.getStockOutProducts()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockOutProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(stockOutProduct.getProductGoodNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockOutProduct.getProductGoodNum())
      );
      outboundItem.setShopId(
        String.valueOf(stockOutProduct.getSid()).equals("null")
          ? null
          : String.valueOf(stockOutProduct.getSid())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            stockOutProduct.getFnsku() == null
              ? null
              : stockOutProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(stockOutProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        stockOutProduct.getStorageBinGoodId(),
        Integer.parseInt(
          String.valueOf(stockOutProduct.getProductGoodNum()).equals("null")
            ? "0"
            : String.valueOf(stockOutProduct.getProductGoodNum())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Normal);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(stockOutProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 提交
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交操作"
  )
  @Override
  public void refer(List<Long> ids) throws Exception {
    if (stockOutReferAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutReferAction.run(ids);
  }

  /**
   * 确认出库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了确认出库操作"
  )
  @Override
  public void confirmOutboundBatch(List<Long> ids) throws Exception {
    if (stockOutConfirmOutboundBatchAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutConfirmOutboundBatchAction.run(ids);
  }

  /**
   * 出库单批量推送领星
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了出库单批量推送领星操作"
  )
  @Override
  public void batchPushLingXing(List<Long> ids) throws Exception {
    if (stockOutBatchPushLingXingAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutBatchPushLingXingAction.run(ids);
  }

  /**
   * 出库并推送领星
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了出库并推送领星操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void outpush(List<Long> ids) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/StockOut_outpush.js",
      ids,
      null,
      this
    );
  }

  /**
   * 出库减去锁定的
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了出库减去锁定的操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void chukujianqusuoding(List<Long> ids) throws Exception {
    List<Long> list = Convert.toList(Long.class, ids);
    for (Long id : list) {
      StockOutVo vo = getVoById(id);
      InventoryOutboundFormVo formVo = prepareChukujianqusuoding(vo);
      inventoryBusinessService.outbound(formVo);
      // 更新成功状态
      StockOut updateStatusEntity = new StockOut();
      updateStatusEntity.setId(id);
      updateStatusEntity.setStatus("CS01");
      updateById(updateStatusEntity);
    }
  }

  /**
   * 准备用于 出库减去锁定的 的参数
   */
  protected InventoryOutboundFormVo prepareChukujianqusuoding(StockOutVo vo)
    throws Exception {
    if (!"CS01".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(StockOutVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Lock);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("其他出库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (StockOutProductItemVo stockOutProduct : vo.getStockOutProducts()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockOutProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(stockOutProduct.getProductGoodNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockOutProduct.getProductGoodNum())
      );
      outboundItem.setShopId(
        String.valueOf(stockOutProduct.getSid()).equals("null")
          ? null
          : String.valueOf(stockOutProduct.getSid())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            stockOutProduct.getFnsku() == null
              ? null
              : stockOutProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(stockOutProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        stockOutProduct.getStorageBinGoodId(),
        Integer.parseInt(
          String.valueOf(stockOutProduct.getProductGoodNum()).equals("null")
            ? "0"
            : String.valueOf(stockOutProduct.getProductGoodNum())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Lock);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(stockOutProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 删除
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了删除操作"
  )
  @Override
  public void omit(List<Long> ids) throws Exception {
    if (stockOutOmitAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutOmitAction.run(ids);
  }

  /**
   * 出库单推送领星
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了出库单推送领星操作"
  )
  @Override
  public void pushLingXing(Long id) throws Exception {
    if (stockOutPushLingXingAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutPushLingXingAction.run(id);
  }

  /**
   * 出库扣减次品
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了出库扣减次品操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void outboundReject(Long id) throws Exception {
    StockOutVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareOutboundReject(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    StockOut updateStatusEntity = new StockOut();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("CS02");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 出库扣减次品 的参数
   */
  protected InventoryOutboundFormVo prepareOutboundReject(StockOutVo vo)
    throws Exception {
    if (!"CS02".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(StockOutVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Defect);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("其他出库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (StockOutProductItemVo stockOutProduct : vo.getStockOutProducts()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockOutProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(stockOutProduct.getProductBadNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockOutProduct.getProductBadNum())
      );
      outboundItem.setShopId(
        String.valueOf(stockOutProduct.getSid()).equals("null")
          ? null
          : String.valueOf(stockOutProduct.getSid())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            stockOutProduct.getFnsku() == null
              ? null
              : stockOutProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(stockOutProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        stockOutProduct.getStorageBinBadId(),
        Integer.parseInt(
          String.valueOf(stockOutProduct.getProductBadNum()).equals("null")
            ? "0"
            : String.valueOf(stockOutProduct.getProductBadNum())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Normal);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(stockOutProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 出库扣减可用
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了出库扣减可用操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void outboundAvailable(Long id) throws Exception {
    StockOutVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareOutboundAvailable(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    StockOut updateStatusEntity = new StockOut();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("CS02");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 出库扣减可用 的参数
   */
  protected InventoryOutboundFormVo prepareOutboundAvailable(StockOutVo vo)
    throws Exception {
    if (!"CS01".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(StockOutVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("其他出库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (StockOutProductItemVo stockOutProduct : vo.getStockOutProducts()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockOutProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(stockOutProduct.getProductGoodNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockOutProduct.getProductGoodNum())
      );
      outboundItem.setShopId(
        String.valueOf(stockOutProduct.getSid()).equals("null")
          ? null
          : String.valueOf(stockOutProduct.getSid())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            stockOutProduct.getFnsku() == null
              ? null
              : stockOutProduct.getFnsku().trim()
          )
          ? null
          : String.valueOf(stockOutProduct.getFnsku().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        stockOutProduct.getStorageBinGoodId(),
        Integer.parseInt(
          String.valueOf(stockOutProduct.getProductGoodNum()).equals("null")
            ? "0"
            : String.valueOf(stockOutProduct.getProductGoodNum())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Normal);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(stockOutProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 提交
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了提交操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void custSubmit(Long id) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/StockOut_custSubmit.js",
      id,
      null,
      this
    );
  }

  /**
   * 下推其他入库单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了下推其他入库单操作"
  )
  @Override
  public void pushStockOut(Long id) throws Exception {
    if (stockOutPushStockOutAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutPushStockOutAction.run(id);
  }

  /**
   * 下推生成入库单和出库单(工厂)
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了下推生成入库单和出库单(工厂)操作"
  )
  @Override
  public void pushStockInAndStockOut(Long id) throws Exception {
    if (stockOutPushStockInAndStockOutAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutPushStockInAndStockOutAction.run(id);
  }

  /**
   * 生成应收单
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了生成应收单操作"
  )
  @Override
  public void createReceivable(Long id) throws Exception {
    if (stockOutCreateReceivableAction == null) {
      throw new Exception("此操作当前不可用");
    }
    stockOutCreateReceivableAction.run(id);
  }

  /**
   * 取消审核
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了取消审核操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void cancelOutbound(Long id) throws Exception {
    StockOutVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareCancelOutbound(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    StockOut updateStatusEntity = new StockOut();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("CS01");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 取消审核 的参数
   */
  protected InventoryOutboundFormVo prepareCancelOutbound(StockOutVo vo)
    throws Exception {
    if (!"CS02".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(StockOutVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消出库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWarehouse())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWarehouse());
    formVo.setModel(PatternEnum.FIFO);
    for (StockOutProductItemVo stockOutProduct : vo.getStockOutProducts()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(stockOutProduct.getProductId());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String.valueOf(stockOutProduct.getQuantity()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(stockOutProduct.getQuantity())
      );
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(stockOutProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    StockOutSearchParamPo search = new StockOutSearchParamPo();
    return MapUtil
      .builder()
      .put("All1", this.baseMapper.all1Count(search))
      .put(
        "ChangesToBeCommitted",
        this.baseMapper.changesToBeCommittedCount(search)
      )
      .put(
        "WaitingForDelivery",
        this.baseMapper.waitingForDeliveryCount(search)
      )
      .put("Done", this.baseMapper.doneCount(search))
      .put("Undone", this.baseMapper.undoneCount(search))
      .build();
  }

  /**
   * 全部
   */
  @Override
  public List<StockOutItemVo> all1(StockOutSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.all1(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<StockOutItemVo> all1Page(StockOutSearchParamPo search) {
    Page<StockOutItemVo> all1Page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return all1Page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return all1Page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    all1Page =
      this.baseMapper.all1Page(
          search.toPage(this.baseMapper.all1Count(search)),
          search
        );
    List<Long> recordIds = all1Page
      .getRecords()
      .stream()
      .map(StockOutItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return all1Page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return all1Page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    all1Page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return all1Page;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 出库单分页查询结果
   */
  @Override
  public Page<?> all1PageWithChildSearch(StockOutSearchParamPo search) {
    return appendWithChild(
      all1Page(search),
      search.toChildSort("stockOutProducts")
    );
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date all1LastUpdateTime(StockOutSearchParamPo search) {
    return this.baseMapper.all1LastUpdateTime(search);
  }

  /**
   * 待提交
   */
  @Override
  public List<StockOutItemVo> changesToBeCommitted(
    StockOutSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.changesToBeCommitted(search);
  }

  /**
   * 待提交分页
   */
  @Override
  public Page<StockOutItemVo> changesToBeCommittedPage(
    StockOutSearchParamPo search
  ) {
    Page<StockOutItemVo> changesToBeCommittedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return changesToBeCommittedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return changesToBeCommittedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    changesToBeCommittedPage =
      this.baseMapper.changesToBeCommittedPage(
          search.toPage(this.baseMapper.changesToBeCommittedCount(search)),
          search
        );
    List<Long> recordIds = changesToBeCommittedPage
      .getRecords()
      .stream()
      .map(StockOutItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return changesToBeCommittedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return changesToBeCommittedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    changesToBeCommittedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return changesToBeCommittedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 出库单分页查询结果
   */
  @Override
  public Page<?> changesToBeCommittedPageWithChildSearch(
    StockOutSearchParamPo search
  ) {
    return appendWithChild(
      changesToBeCommittedPage(search),
      search.toChildSort("stockOutProducts")
    );
  }

  /**
   * 查询待提交最后更新时间
   * @param search 查询条件
   * @return 待提交最后更新时间
   */
  @Override
  public Date changesToBeCommittedLastUpdateTime(StockOutSearchParamPo search) {
    return this.baseMapper.changesToBeCommittedLastUpdateTime(search);
  }

  /**
   * 待出库
   */
  @Override
  public List<StockOutItemVo> waitingForDelivery(StockOutSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.waitingForDelivery(search);
  }

  /**
   * 待出库分页
   */
  @Override
  public Page<StockOutItemVo> waitingForDeliveryPage(
    StockOutSearchParamPo search
  ) {
    Page<StockOutItemVo> waitingForDeliveryPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return waitingForDeliveryPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return waitingForDeliveryPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    waitingForDeliveryPage =
      this.baseMapper.waitingForDeliveryPage(
          search.toPage(this.baseMapper.waitingForDeliveryCount(search)),
          search
        );
    List<Long> recordIds = waitingForDeliveryPage
      .getRecords()
      .stream()
      .map(StockOutItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return waitingForDeliveryPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return waitingForDeliveryPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    waitingForDeliveryPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return waitingForDeliveryPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 出库单分页查询结果
   */
  @Override
  public Page<?> waitingForDeliveryPageWithChildSearch(
    StockOutSearchParamPo search
  ) {
    return appendWithChild(
      waitingForDeliveryPage(search),
      search.toChildSort("stockOutProducts")
    );
  }

  /**
   * 查询待出库最后更新时间
   * @param search 查询条件
   * @return 待出库最后更新时间
   */
  @Override
  public Date waitingForDeliveryLastUpdateTime(StockOutSearchParamPo search) {
    return this.baseMapper.waitingForDeliveryLastUpdateTime(search);
  }

  /**
   * 已完成
   */
  @Override
  public List<StockOutItemVo> done(StockOutSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.done(search);
  }

  /**
   * 已完成分页
   */
  @Override
  public Page<StockOutItemVo> donePage(StockOutSearchParamPo search) {
    Page<StockOutItemVo> donePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return donePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return donePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    donePage =
      this.baseMapper.donePage(
          search.toPage(this.baseMapper.doneCount(search)),
          search
        );
    List<Long> recordIds = donePage
      .getRecords()
      .stream()
      .map(StockOutItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return donePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return donePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    donePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return donePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 出库单分页查询结果
   */
  @Override
  public Page<?> donePageWithChildSearch(StockOutSearchParamPo search) {
    return appendWithChild(
      donePage(search),
      search.toChildSort("stockOutProducts")
    );
  }

  /**
   * 查询已完成最后更新时间
   * @param search 查询条件
   * @return 已完成最后更新时间
   */
  @Override
  public Date doneLastUpdateTime(StockOutSearchParamPo search) {
    return this.baseMapper.doneLastUpdateTime(search);
  }

  /**
   * 已撤销
   */
  @Override
  public List<StockOutItemVo> undone(StockOutSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.undone(search);
  }

  /**
   * 已撤销分页
   */
  @Override
  public Page<StockOutItemVo> undonePage(StockOutSearchParamPo search) {
    Page<StockOutItemVo> undonePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return undonePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return undonePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    undonePage =
      this.baseMapper.undonePage(
          search.toPage(this.baseMapper.undoneCount(search)),
          search
        );
    List<Long> recordIds = undonePage
      .getRecords()
      .stream()
      .map(StockOutItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return undonePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return undonePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    undonePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return undonePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 出库单分页查询结果
   */
  @Override
  public Page<?> undonePageWithChildSearch(StockOutSearchParamPo search) {
    return appendWithChild(
      undonePage(search),
      search.toChildSort("stockOutProducts")
    );
  }

  /**
   * 查询已撤销最后更新时间
   * @param search 查询条件
   * @return 已撤销最后更新时间
   */
  @Override
  public Date undoneLastUpdateTime(StockOutSearchParamPo search) {
    return this.baseMapper.undoneLastUpdateTime(search);
  }
}
